package com.powernode.config;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.powernode.constant.OrderConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

@Configuration
public class MessageConfig implements CommandLineRunner {
    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.appSecret}")
    private String appSecret;
    @Value("${wx.tokenUrl}")
    private String tokenUrl;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //获取到token
    @Scheduled(initialDelay = 2 * 60 * 1000, fixedDelay = 2 * 60 * 1000)
    public void msgToken() {
        //获得请求路径
        String url = String.format(tokenUrl, appId, appSecret);
        JSONObject tokenJson = JSON.parseObject(HttpUtil.get(url));
        //获取到token和过期时间
        String access_token = tokenJson.getString("access_token").trim();
        Long expires_in = tokenJson.getLong("expires_in");
        //将其存到redis中
        stringRedisTemplate.opsForValue().set(OrderConstant.ACCESS_TOKEN_KEY, access_token, expires_in);
    }

    @Override
    public void run(String... args) throws Exception {
        msgToken();
    }
}
